package org.sjsu.freedoor.model;

import java.util.Collection;
import java.util.HashMap;

public class CommunityList {

	// storage for community objects, using URL as its key
	private HashMap<String,Community> communities;
	
	public CommunityList(){
		communities = new HashMap<String,Community>();
	}
	
	
	public int size(){
		return communities.size();
	}
	
	// add community if URL hasn't been added yet
	public boolean addCommunity(Community com){
		if(!communities.containsKey(com.getURL())){
			communities.put(com.getURL(),com);
			return true;
		}
		
		return false;
	}
	
	// add community using Strings
	public boolean addCommunity(String description, String url){
		
		if(!communities.containsKey(url)){
			Community newCom = new Community(description, url);
			communities.put(url, newCom);
			return true;
		}
		
		return false;
	}
	
	// get community by URL
	public Community getCommunitiesByURL(String url){
		if(communities.containsKey(url)){
			return communities.get(url);
		}
		
		return null;
	}
	
	// return all communites in an array
	public Community[] toArray(){
		Collection<Community> coms = communities.values();
		
		Community[] comArr = new Community[coms.size()];
		int i = 0;
		for( Community com : coms){
			comArr[i] = com;
			i++;
		}
		
		return comArr;

	}
	
	public Collection<Community> toCollection(){
		return communities.values();
	}
	
	public String toJSON(){
		
		
		Community[] coms = toArray();
		String ret = "{\"communities\":[";
		
		for(int i=0; i<coms.length; i++){
			ret +=coms[i].toJSON();
			
			//add a comma expect for the last element
			if(i < coms.length - 1)
				ret += ",";
		}
		
		ret += "]}";
		
		return ret;
		
	}
}
